package com.rightsidetech.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.exception.BizException;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.news.*;
import com.rightsidetech.system.dtos.response.news.AgentAppPageResp;
import com.rightsidetech.system.dtos.response.news.NewsDetailResp;
import com.rightsidetech.system.dtos.response.news.NewsPageResp;
import com.rightsidetech.system.entity.news.SysNews;
import com.rightsidetech.system.mapper.SysNewsFileMapper;
import com.rightsidetech.system.mapper.SysNewsMapper;
import com.rightsidetech.system.service.SysNewsService;
import org.hibernate.validator.constraints.Range;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("sysNewsService")
public class SysNewsServiceImpl implements SysNewsService {


    @Resource
    private SysNewsMapper sysNewsMapper;
    @Resource
    private SysNewsFileMapper sysNewsFileMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData saveNews(NewsSaveReq req, String createrName, Long createrId) throws Exception {
        ResponseData check = check(req);
        if (check != null) {
            return check;
        }
        Long count = sysNewsMapper.selectCountByTopic(req.getTopic(), req.getPlatform());
        if (count > 0) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "同平台标题已存在");
        }
        SysNews record = getSysNews(req);
        record.setCreatedAt(new Date());
        record.setCreaterId(createrId);
        record.setCreaterName(createrName);
        if (sysNewsMapper.insertSelective(record) <= 0) {
            throw new BizException("数据库操作时出错");
        }
        List<FileUriType> files = req.getFile();
        if (CollUtil.isNotEmpty(files)) {
            Map<String, Object> map = new HashMap<>();
            map.put("newsId", record.getId());
            map.put("list", files);
            if (sysNewsFileMapper.insertList(map) <= 0) {
                throw new BizException("数据库操作时出错");
            }
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    private SysNews getSysNews(NewsSaveReq req) {
        SysNews news = new SysNews();
        news.setTopic(req.getTopic());
        news.setPlatform(req.getPlatform());
        news.setTypeId(req.getTypeId());
        news.setDescribe(req.getDescribe());
        news.setReleaseDate(req.getReleaseDate());
        news.setIsDeleted((byte) 0);
        return news;
    }

    private ResponseData check(NewsSaveReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<FileUriType> files = req.getFile();
        if (CollUtil.isNotEmpty(files)) {
            for (FileUriType file : files) {
                ConstraintViolation validate1 = BeanValidator.validate(file);
                if (validate1 != null) {
                    return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate1.getMessage());
                }
            }
        }
        return null;
    }

    @Override
    public ResponseData<PageInfo<NewsPageResp>> page(NewsPageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<NewsPageResp> result = sysNewsMapper.selectPageList(req);
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public ResponseData<NewsDetailResp> detail(Long id) {
        if (id == null || id < 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "id不可为空或小于1");
        }
        NewsDetailResp result = sysNewsMapper.selectDetail(id);
        if (ObjectUtil.isEmpty(result)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到数据");
        }
        result.setFiles(sysNewsFileMapper.selectListByNewsId(id));
        return ResponseData.success(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData update(NewsUpdateReq req, String updaterName, Long updaterId) throws Exception {
        ResponseData check = check(req);
        if (check != null) {
            return check;
        }
        SysNews sysNews = sysNewsMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(sysNews) || sysNews.getIsDeleted() == 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到需要操作数据");
        }
        if (!sysNews.getTopic().equals(req.getTopic())) {
            if (sysNewsMapper.selectCountByTopic(req.getTopic(), req.getPlatform()) > 0) {
                return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "同平台标题已存在");
            }
        }
        sysNewsFileMapper.deleteByNewsId(sysNews.getId());
        if (CollUtil.isNotEmpty(req.getFile())) {
            Map<String, Object> map = new HashMap<>();
            map.put("newsId", sysNews.getId());
            map.put("list", req.getFile());
            if (sysNewsFileMapper.insertList(map) <= 0) {
                throw new BizException("数据库操作出错");
            }
        }
        SysNews record = getSysNews(req);
        record.setId(sysNews.getId());
        record.setUpdatedAt(new Date());
        record.setUpdaterId(updaterId);
        record.setUpdaterName(updaterName);
        if (sysNewsMapper.updateByPrimaryKeySelective(record) <= 0) {
            throw new BizException("数据库操作出错");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData del(DelReq req, Long id, String name) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysNews sysNews = sysNewsMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(sysNews) || sysNews.getIsDeleted() == 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到需要操作数据");
        }
        sysNews = new SysNews();
        sysNews.setId(req.getId());
        sysNews.setIsDeleted((byte) 1);
        sysNews.setUpdaterId(id);
        sysNews.setUpdaterName(name);
        sysNews.setUpdatedAt(new Date());
        if (sysNewsMapper.updateByPrimaryKeySelective(sysNews) <= 0) {
            return ResponseData.fail("更新失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData offNews(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysNews sysNews = sysNewsMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(sysNews) || sysNews.getIsDeleted() == 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到需要操作数据");
        }
        if (sysNews.getStatus() == 1) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "此新闻已经下架");
        }
        sysNews = new SysNews();
        sysNews.setId(req.getId());
        sysNews.setStatus((byte) 1);
        if (sysNewsMapper.updateByPrimaryKeySelective(sysNews) <= 0) {
            return ResponseData.fail("更新失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<PageInfo<AgentAppPageResp>> appPage(AgentAppPageReq req, Byte platform) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<AgentAppPageResp> result = sysNewsMapper.selectAppPageList(req.getTypeId(), platform);
        return ResponseData.success(new PageInfo<>(result));
    }
}
